<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Ajax接口工具</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/base.css">
</head>

<body>
    <div id="app" @click="historyShow = false" v-cloak>
        <div class="container">
            <h3 class="text-center">Ajax接口工具</h3>
            <br>
            <div class="input-group">
                <span class="input-group-addon">公用地址</span>
                <input type="text" class="form-control" v-model="baseURL" placeholder="请输入公用请求地址 ">
            </div>
            <div class="input-group">
                <span class="input-group-addon">请求地址</span>
                <input type="text" class="form-control" @click.stop="historyShow = true" @keyup="search" v-model="url" placeholder="请输入请求地址">
                <div class="toggle" v-show="historyShow">
                    <ul>
                        <li v-for="(v,index) in historys" @click="selectHistory(index)">{{v.baseURL + v.url}}
                            <span class="date">{{v.upDate}}</span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="input-group">
                <span class="input-group-addon">请求方式</span>
                <select class="form-control" v-model="type">
                    <option value="GET">GET</option>
                    <option value="POST">POST</option>
                </select>
            </div>
            <div>请求头</div>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width:100px;">key</th>
                            <th>value</th>
                            <th style="width:100px;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(v,index) in headers" :key="index">
                            <td>
                                <input type="text" class="form-control" v-model=v.key>
                            </td>
                            <td>
                                <input type="text" class="form-control" v-model=v.value>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-success" @click="addHeader" v-if="index === 0">添加
                                </button>
                                <button class="btn btn-danger btn-sm" v-else @click="removeHeader(index)">删除
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="input-group">
                <span class="input-group-addon top">请求参数</span>
                <textarea name="" style="width: 100%;" class="form-control" v-model="body" placeholder="请输入请求参数（json格式）"></textarea>
            </div>
            <div class="text-center">
                <button class="btn btn-info submit" @click="submit">提交</button>
                <button class="btn" @click="resetForm">清空</button>
            </div>
            <br>
            <div>
                <pre class="returndata" v-html='res'></pre>
            </div>
        </div>
    </div>
</body>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.17.1/axios.js"></script>
<script src="js/formatJson.js"></script>
<script>
let vm = new Vue({
    el: '#app',
    data: {
        historyShow: false,
        baseURL: '',
        url: '',
        type: 'POST',
        headers: [{
            key: '',
            value: ''
        }],
        body: '',
        res: '',
        historys: []
    },
    mounted() {
        this.historys = this.getHistory();
    },
    methods: {
        submit() {
            let type = this.type;
            let head = this.headers;
            let url = this.baseURL + this.url;
            let data = {};
            if (this.body.trim().length === 0 || this.body === undefined) {
                data = {};
            } else {
                data = JSON.parse(this.body)
            }
            let headers = {};
            for (let i of head) {
                headers[i.key] = i.value;
            }
            //  储存为历史
            this.save(headers);
            //  更新历史
            this.historys = this.getHistory();
            //  提交
            if (type === 'POST') {
                axios({
                    url,
                    method: type,
                    data
                }).then(res => {
                    let data = JSON.stringify(res.data)
                    this.res = formatJson(data);

                })
            } else if (type === 'GET') {
                axios({
                    url,
                    method: type,
                    params: data
                }).then(res => {
                    let data = JSON.stringify(res.data)
                    this.res = formatJson(data);
                })
            }
        },
        // 添加请求头
        addHeader() {
            let obj = {
                key: '',
                value: ''
            };
            this.headers.push(obj);
        },
        // 删除请求头
        removeHeader(index) {
            this.headers.splice(index, 1);
        },
        // 清空表单
        resetForm() {
            this.url = '';
            this.body = '';
            this.res = '';
        },
        // 保存历史记录
        save(headers = {}) {
            let type = this.type;
            let url = this.url;
            let body = this.body;
            let baseURL = this.baseURL;
            let D = new Date();
            let upDate = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + (D.getDate()) + ' ' + D.getHours() + ':' + D.getMinutes() + ':' + D.getSeconds();
            let obj = {
                url,
                body,
                baseURL,
                type,
                headers,
                upDate
            };
            // 取出储存的数据并且格式化
            let storageData = this.getHistory();

            // 判断是否已存在此条记录
            let ishave = false;
            console.log(ishave)
            for (let i of storageData) {
                let u = this.baseURL + this.url;
                let iu = i.baseURL + i.url;
                if (u === iu) {
                    storageData[i] = obj;
                    ishave = true;
                }
            }
            if (!ishave) {
                storageData.push(obj);
            }
            // 转为JSON储存
            localStorage.setItem('historyData', JSON.stringify(storageData));
        },
        // 取出历史记录并格式化
        getHistory() {
            let storageData = localStorage.getItem('historyData');
            if (storageData === null ||
                storageData.trim().length === 0 ||
                storageData === undefined) {
                storageData = [];
            } else {
                storageData = JSON.parse(storageData);
            }
            return storageData;
        },
        // 选择历史记录事件
        selectHistory(index) {
            let data = this.historys[index];
            this.url = data.url;
            this.baseURL = data.baseURL;
            this.type = data.type;
            this.body = data.body;
            let h = [];
            for (let i in data.headers) {
                let a = {
                    key: i,
                    value: data.headers[i]
                };
                h.push(a);
            }
            this.headers = h;
            this.historyShow = false;
        },
        search() {
            let val = this.baseURL + this.url;
            let his = this.getHistory();
            let h = []
            for (let i of his) {
                let u = i.baseURL + i.url;
                if (u.indexOf(val) != '-1') {
                    h.push(i);
                }
            }
            if (val.trim().length === 0 || val === null || val === undefined) {
                this.historys = this.getHistory();
            } else {
                this.historys = h;
            }
        }
    }
});
</script>

</html>